package com.zhanjixun.weixin;

import com.google.common.collect.Lists;
import com.zhanjixun.weixin.domain.ContactMember;
import com.zhanjixun.weixin.domain.WxInitDataDTO;
import com.zhanjixun.weixin.domain.WxMsg;
import com.zhanjixun.weixin.frame.ImageFrame;
import com.zhanjixun.weixin.runnable.SyncCheckAsyncTask;
import com.zhanjixun.weixin.service.WxService;
import com.zhanjixun.weixin.service.impl.WxServiceImpl;
import com.zhanjixun.weixin.utils.U;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;

import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 网页微信
 *
 * @author :zhanjixun
 * @date : 2018/10/19 23:37
 */
@Log4j
public class Weixin {
    @Getter
    private final WxService wxService = new WxServiceImpl();
    //登录二维码窗体
    private final ImageFrame imageFrame = new ImageFrame();

    //初始化信息
    @Getter
    private WxInitDataDTO wxInitDataDTO;
    //通讯录
    @Getter
    private List<ContactMember> wxContact;
    //同步检查线程
    private final SyncCheckAsyncTask syncCheckAsyncTask = new SyncCheckAsyncTask(this);

    //接收的聊天记录
    @Getter
    private final LinkedList<WxMsg> msgHistory = Lists.newLinkedList();
    //发送的聊天记录
    @Getter
    private final LinkedList<WxMsg> msgSendHistory = Lists.newLinkedList();

    //发消息工具
    @Getter
    private final Messenger messenger = new Messenger(this);
    //资源下载器
    @Getter
    private final Downloader downloader = new Downloader(this);
    //消息处理器
    @Setter
    @Getter
    private WxMsgHandler msgHandler;
    //群聊消息处理器[区分私聊处理器]
    @Setter
    @Getter
    private WxMsgHandler groupMsgHandler;

    private static Weixin weixin;

    private Weixin() {
    }

    public static Weixin getInstance() {
        if (weixin == null) {
            synchronized (Weixin.class) {
                if (weixin == null) {
                    weixin = new Weixin();
                }
            }
        }
        return weixin;
    }

    /**
     * 直接登录，会弹出jFrame框显示二维码
     */
    public void login() {
        String uuid = wxService.getUUID();
        log.debug("获取UUID : " + uuid);

        BufferedImage qrCodeImage = wxService.getQRCodeImage(uuid);
        String imageFilePath = U.downloadImage(qrCodeImage, "QRCode.jpg");
        log.debug("下载登录二维码：" + imageFilePath);

        imageFrame.setImage(imageFilePath);
        imageFrame.setVisible(true);
        log.debug("请扫描二维码");
        //System.out.println(QRCodeUtil.toCharMatrix(qrCodeImage));

        while (true) {
            Map<String, String> scanStatus = wxService.getScanStatus(uuid);
            if (scanStatus.get("code").equals("200")) {
                imageFrame.setVisible(false);
                imageFrame.dispose();
                break;
            }
            if (scanStatus.get("code").equals("201")) {
                log.debug("请在手机端确认登录");
                imageFrame.setImage(U.base64Image(scanStatus.get("userAvatar"), "userAvatar.jpg"));
            }
            if (scanStatus.get("code").equals("408")) {
                continue;
            }
            if (scanStatus.get("code").equals("400")) {
                log.debug("扫码超时");
                imageFrame.setImage("break.png");
            }
        }

        wxService.getWxTicket();

        wxInitDataDTO = wxService.webWxInit();
        log.debug(String.format("欢迎：%s %s", wxInitDataDTO.getUser().getNickName(), wxInitDataDTO.getUser().getUserName()));
        //log.debug(String.format("聊天列表[%s]", wxInitDataDTO.getContactList().stream().map(ContactMember::getNickName).collect(Collectors.joining(","))));

        wxContact = wxService.getContact();
        log.debug(String.format("获取通讯录：好友%d位 公众号%d个", wxContact.stream().filter(d -> StringUtils.length(d.getUserName()) == 65).count(), wxContact.stream().filter(d -> StringUtils.length(d.getUserName()) == 33).count()));

        wxService.statusNotify();
        //启动同步线程
        new Thread(syncCheckAsyncTask).start();
    }
}
